<template>
	<view class="container page">
		<view class="section-wrapper section2">
			<view class="input-v">
				<view class="textarea-v">
					<textarea v-model="formData.questionContext" placeholder="请写下你的评论~" />
				</view>
			</view>
			<view class="media-v">
				<template v-if="imgList.length > 0">
					<view v-for="(item, index) in imgList" class="media-item-com media-show-item">
						<view class="img-v">
							<image :src="item" mode="aspectFit"></image>
						</view>
						<view class="close" @click="delImg(item, index)">X</view>
					</view>
				</template>
				<view v-if="!(imgList.length >= imgNum)" class="media-item-com media-item" @click="chooseImg">
					<view class="img-v">
						<image src="../../static/images/icon-imgUpload.png" mode="aspectFit"></image>
					</view>
					<view class="txt">添加</view>
				</view>
			</view>
		</view>
		<form></form>
	</view>
</template>

<script>
	//发布评论
	import {
		_usertalk
	} from '@/service/news.js'

	import {
		_image
	} from '@/service/news.js'

	import { _talksearch} from '@/service/news.js'
	import axios from 'axios'
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		data() {
			return {
				ifShow: false,
				formData: {
					extendColumn1: '', // 类型 1图片 2 视频
					questionContext: '', // 文章类容
				},
				imgList: [], // 图片路径
				imgFileList: [], // 图片文件
				disabled: false,
				imgNum: 6,
				account_user: '',
				image:[],
				// imagefile:[]
			};
		},


		computed: {
			...mapState(['hasLogin', 'isBindPhone']),
			sessionId() {
				let url;
				// #ifdef H5  
				var reg = new RegExp("(^|&)state=([^&]*)(&|$)", "i");
			 var r = window.location.search.substr(1).match(reg)[2];
				if (r === '10') { // 如果是螃蟹的，因为印刷的二维码不对，这里只能兼任写死
					url = r + window.location.host;
				} else {
					url = r.split('_')[0] + window.location.host;
				}
				// #endif
				//#ifdef APP-PLUS
				let {
					shopIdApp
				} = this.$json('appPublic');
				url = shopIdApp;
				//#endif
				return uni.getStorageSync(`sessionId_` + url);
			},
			shopId() {
				// #ifdef H5  
				var reg = new RegExp("(^|&)state=([^&]*)(&|$)", "i");
				var r = window.location.search.substr(1).match(reg);
				let url;
				if (r === '10') { // 如果是螃蟹的，因为印刷的二维码不对，这里只能兼任写死
					url = r + window.location.host;
				} else {
					url = r[2].split('_')[0] + window.location.host;
				}
				return uni.getStorageSync(`SHOPID_` + url);
				// #endif
				//#ifdef APP-PLUS
				let {
					shopIdApp
				} = this.$json('appPublic');
				return shopIdApp;
				//#endif	
			},
			baseUrl() {
				return this.$json('apiUrlPublic').baseUrl;
			},
			theUrl() {
				let url;
				// #ifdef H5  
				var reg = new RegExp("(^|&)state=([^&]*)(&|$)", "i");
				var r = window.location.search.substr(1).match(reg)[2];
				if (r === '10') { // 如果是螃蟹的，因为印刷的二维码不对，这里只能兼任写死
					url = r + window.location.host;
				} else {
					url = r.split('_')[0] + window.location.host;
				}
				// #endif
				//#ifdef APP-PLUS
				let {
					shopIdApp
				} = this.$json('appPublic');
				url = shopIdApp;
				//#endif
				return url;
			}
		},
		watch: {
			hasLogin(v) {
				if (v && !this.isBindPhone) {
					uni.navigateTo({
						url: `/pages/system/bindPhone?type=noBind`,
					});
				}
			}
		},
		onNavigationBarButtonTap(obj) {
			console.log(obj);
			// if (this.imgList.length == 0 && this.formData.articlecontext == '') {
			// 	this.$api.msg('请添加提问信息');
			// 	return;
			// }
			if (this.formData.questionContext == '') {
				this.$api.msg('请添加提问信息');
				return;
			}
			if (this.disabled) {
				this.$api.msg('正在发布，不可重复发布');
			} else {
				uni.showLoading({
					title: ''
				});
				this.disabled = true;
				this.doAddApi();
				
			}
		},
		onLoad() {
			let newdata;
			try {
				const value = uni.getStorageSync('userInfo');
				if (value != null) {
					this.account_user = value.accountNum
				}
			} catch (e) {
				console.error(e);
			}
			// this.getNewTime()
			// this.talksearch()
		},
		onShow() {
			// if (this.hasLogin && !this.isBindPhone) {
			// 	uni.navigateTo({
			// 		url: `/pages/system/bindPhone?type=noBind`,
			// 	});
			// }
		},
		methods: {
			navTo(url) {
				uni.navigateTo({
					url: url
				})
			},
			// 添加动态接口调用
			async doAddApi() {
				let data = {
					account_user: this.account_user,
					acc_user:'',
					talk_user: this.formData.questionContext,
					image1: this.image[0], // 直接使用数组中的对应索引位置的值
					image2: this.image[1],
					image3: this.image[2],
					image4: this.image[3],
					image5: this.image[4],
					image6: this.image[5]
				}
				let res = await _usertalk(data)
				console.log(this.account_user, this.formData.questionContext)
				console.log(res)
				if (res.flag == true) {
					setTimeout(() => {
						this.$api.msg('提问已发布！');
						// this.goToBack();
						// this.navTo('/pages/trends/trends')
						uni.navigateBack({
						  delta: 1 // 返回到上一个页面
					    });
					}, 500);
				} else {
					setTimeout(() => {
						this.$api.msg('发布失败！');
					}, 500)
				}
			},
			showFailReason(data) {
				// 根据后台确定，所有错误都直接显示message
				this.$api.msg(data.message);
			},

			// 选择图片
			chooseImg() {
				this.ifShow = false;
				let s = this.imgNum - this.imgList.length;
				//打开本地相册选择图片
				uni.chooseImage({
					count: s, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {
						console.log(res);
						if (s >= res.tempFilePaths.length) {
							for (let v of res.tempFilePaths) {
								this.imgList.push(v);
							}
							for (let v of res.tempFiles) {
								this.imgFileList.push(v);
							}
						}
						this.uploadImages()
					},
					fail: (res) => {
						this.$api.msg('上传图片失败');
					}
				});
			},
			
			// 删除图片
			delImg(item, index) {
				this.imgList.splice(index, 1);
				this.imgFileList.splice(index, 1);
			},
			
			async uploadImages() {
			  try {
			    const promises = this.imgFileList.map(async (imgFile) => {
			      const tempFilePath = imgFile.path;
			      const [error, res] = await uni.uploadFile({
			        url: 'http://43.142.102.167:8088/common/images',
			        filePath: tempFilePath,
			        name: 'image',
			        formData: {
			          shopTalkNumber: this.imgFileList.length
			        }
			      });
			      if (error) {
			        throw new Error(error);
			      }
			      console.log(res.data);   // 上传成功后的返回数据
			      const responseData = JSON.parse(res.data);
			      console.log(responseData.data);
			      // this.image = responseData.data;
				  // this.image.push(responseData.data); // 将返回的图片数据添加到this.image数组中 这是以数组的方式传入
				  this.image = this.image.concat(responseData.data);//这是以数组的方式传入
			      console.log(this.image);
			    });
			
			    await Promise.all(promises);
			    console.log('上传成功');
			  } catch (error) {
			    console.error(error);
			    this.$api.msg('上传图片失败');
			  }
			},

			
			// //上传图片 网页端
			// async uploadImages() {
			// 	try {
			// 		const formData = new FormData();
			// 		//上传多张图片
			// 		for (let i = 0; i < this.imgFileList.length; i++) {
			// 			formData.append('image', this.imgFileList[i]);
			// 		}
			// 		formData.append('shopTalkNumber', this.imgFileList.length);
			// 		//添加单张图像
			// 		// const res = await axios.post('http://43.142.102.167:8088/common/image', formData, {
			// 		// 	headers: {
			// 		// 		'Content-Type': 'multipart/form-data'
			// 		// 	}
			// 		// });
			// 		const res = await axios.post('http://43.142.102.167:8088/common/images', formData, {
			// 			headers: {
			// 				'Content-Type': 'multipart/form-data'
			// 			}
			// 		});
			// 		console.log(res.data); // 上传成功后的返回数据

			// 		this.image=res.data.data
			// 		console.log(this.image)
					
			// 		console.log('上传成功');
			// 	} catch (error) {
			// 		console.error(error);
			// 		this.$api.msg('上传图片失败');
			// 	}
			// },

			// 跳转列表页面
			goToBack() {
				// uni.redirectTo({
				// 	url: `/pages/group1/evaluateInfo?sequencecode=${this.formData.crabid}`
				// });
				uni.navigateBack({

				})
			},

			
			// //根据评论号查询评论
			// async talksearch(){
			// 	let data={
			// 		talk_number:this.time
			// 	}
			// 	let res=await _talksearch(data)
			// 	console.log(res.data)
			// }
		},
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #f7f7f7;
	}

	.container {
		/* #ifdef APP-PLUS */
		height: 100vh;
		background-color: #f7f7f7;
		/* #endif */
		position: relative;
		padding: 20upx 40upx;
	}

	.section-wrapper {
		background-color: #fff;
		border-radius: 20upx;


	}

	.section2 {
		margin-top: 20upx;
		padding: 26.66upx 20upx 20upx;
	}

	.input-v {
		position: relative;
	}

	.textarea-v {
		padding: 8upx 10upx;

		textarea {
			width: auto;
			height: 240upx;
			font-size: 29.33upx;
			line-height: 41.33upx;
		}
	}

	.media-v {
		display: flex;
		justify-content: flex-start;
		flex-wrap: wrap;
		margin-top: 15upx;

		.media-item-com {
			width: 140upx;
			height: 140upx;
			border-radius: 13.33upx;
			margin-bottom: 20upx;

			&:not(:nth-child(4n+4)) {
				margin-right: 20upx;
			}
		}

		.media-item {
			border: 1px dashed #CCCCCC;
			text-align: center;
			padding-top: 31.33upx;

			.txt {
				font-size: 22.66upx;
				line-height: 32upx;
				margin-top: 14.66upx;
				color: #B3B3B3;
			}
		}

	}

	.img-v {
		width: 50.66upx;
		height: 50.66upx;
		margin: auto;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.media-v {
		display: flex;
		justify-content: flex-start;
		flex-wrap: wrap;
		margin-top: 15upx;

		.media-item-com {
			width: 140upx;
			height: 140upx;
			border-radius: 13.33upx;
			margin-bottom: 20upx;

			&:not(:nth-child(4n+4)) {
				margin-right: 20upx;
			}
		}

		.media-item {
			// width: 153.33upx;
			// height: 153.33upx;
			border: 1px dashed #CCCCCC;
			text-align: center;
			padding-top: 31.33upx;

			// margin-right: 30upx;
			.txt {
				font-size: 22.66upx;
				line-height: 32upx;
				margin-top: 14.66upx;
				color: #B3B3B3;
			}

			.img-v {
				width: 50.66upx;
				height: 50.66upx;
				margin: auto;
			}
		}

		.media-show-item {
			position: relative;
			// width: 153.33upx;
			// height: 153.33upx;
			// margin-right: 30upx;
			border: 1px solid #ececec;

			.img-v {
				width: 100%;
				height: 100%;
			}

			video {
				width: 100%;
				height: 100%;
			}

			.close {
				position: absolute;
				top: -15upx;
				right: -15upx;
				display: block;
				content: 'X';
				width: 30upx;
				height: 30upx;
				font-size: 14upx;
				line-height: 30upx;
				text-align: center;
				background-color: rgba(0, 0, 0, 0.3);
				border-radius: 50%;
				color: #fff;
			}

			// &::after{
			// 	
			// }
		}
	}
</style>
